# -*- coding: latin-1 -*-

import OGBot
from bottle import run, static_file, route, get, post, debug, request, response, abort, redirect #@UnresolvedImport #@UnusedImport
from mako.template import Template #@UnresolvedImport
from mako.lookup import TemplateLookup

import hashlib, random, logging, os, json

logging.basicConfig(filemode="w",format="<span class=\"log-%(levelname)s\">%(asctime)s: %(message)s<br /></span>",level=logging.DEBUG,filename='web/ogbot.log.html')
logging.info("OGBot (re)started")

bot = OGBot.OGBot()
bot.start("localhost","root","","ogame")
logging.info("DB Connection established")

lkup = TemplateLookup(directories=[os.getcwd()])

session = {}

def checkLogin(sess):
    global session
    if sess in session:
        return session[sess]
    else:
        redirect("/")

def checkHandle(player_id):
    if player_id not in bot.handles:
        bot.create_handle(player_id)
        bot.handles[player_id].connect()

def checkQueue(player_id):
    if player_id not in bot.queues:
        bot.create_queue(player_id)

@get('/ogbot.log.html')
def get_log():
    return static_file("ogbot.log.html",root="web/")

@get('/')
def get_login():
    login_tpl = Template(filename="web/login.html")
    return login_tpl.render(exception=None)

@post('/')
def post_login():
    if not request.forms.get('uni') or not request.forms.get('name') or not request.forms.get('pass'):
        abort(403)
    uni = request.forms.get('uni')
    user = request.forms.get('name')
    pw = request.forms.get('pass')
    
    try:
        bot.check_login(uni, user, pw)
    except BaseException, e:
        logging.warning("Logging for player %s failed (%s - using password: %s)",user,uni,pw)
        login_tpl = Template(filename="web/login.html")
        return login_tpl.render(exception = e.message)
    logging.info("Player %s logged in (%s)",user,uni)
    rand = hashlib.md5(str(random.randint(100000,999999))).hexdigest()
    global session
    session.update({ rand: bot.get_player_id(uni, user) })
    response.set_cookie("session",rand)
    redirect("/main/index.html")

@get('/register')
def get_register():
    register_tpl = Template(filename="web/register.html")
    return register_tpl.render(exception=None)

@post('/register')
def post_register():
    if not request.forms.get('uni') or not request.forms.get('name') or not request.forms.get('pass'):
        abort(403)
    uni = request.forms.get('uni')
    user = request.forms.get('name')
    pw = request.forms.get('pass')

    try:
        bot.register_player(uni,user,pw)
    except BaseException, e:
        logging.warning("Failed registration for player %s (%s - using password: %s)",user,uni,pw)
        register_tpl = Template(filename="web/register.html")
        return register_tpl.render(exception=e.message)
    logging.info("Player %s registered (%s)",user,uni)
    redirect("/")

@route('/main/:name')
def get_main(name):
    pid = checkLogin(request.get_cookie("session"))
    checkHandle(pid)
    checkQueue(pid)

    logging.debug("Got main request: %s",name)
    
    main_tpl = Template(filename="web/main/"+name,lookup=lkup)
    return main_tpl.render(bot=bot,pid=pid,request=request)




@route('/static/:name')
def server_static(name):
    logging.debug("Got static request: %s",name)
    return static_file(name,root="web/static")

@route('/ajax/:name')
def get_ajax(name):
    pid = checkLogin(request.get_cookie("session"))
    checkHandle(pid)

    logging.debug("Got AJAX request: %s",name)

    if name == "techtree":
        return bot.handles[pid].fetchTechtree()
    elif name == "dumptechtree":
        bot.dump_techtree(pid)
    elif name == "production":
        return bot.handles[pid].fetchProduction()
    elif name == "resources":
        return bot.handles[pid].fetchResources()
    elif name == "resourcebuildings":
        return bot.handles[pid].fetchResourceBuildings()
    elif name == "defense":
        return bot.handles[pid].fetchDefense()
    elif name == "fleet":
        return bot.handles[pid].fetchFleet()
    elif name == "stationbuildings":
        return bot.handles[pid].fetchStationBuildings()
    elif name == "metadata":
        return bot.handles[pid].fetchMetadata()
    elif name == "queueadd":
        if not request.query.id or not request.query.planet or not request.query.count:
            abort(403)
        bot.queues[pid].add(int(request.query.id),int(request.query.planet),int(request.query.count))
        return "Done"
    elif name == "queuedel":
        if not request.query.id:
            abort(403)
        bot.queues[pid].rem(int(request.query.id))
        return "Done"
    elif name == "queueget":
        if not request.query.planet:
            abort(403)
        return json.dumps(bot.queues[pid].get(int(request.query.planet)))
    #elif name == "calctime":
    #    if not request.query.id:
    #        abort(403)
    #    tech_id = int(request.query.id)
    #    if tech_id < 100:
    #        return bot.handles[pid].calcBuildTime(tech_id)
    #    elif tech_id < 200:
    #        return bot.handles[pid].calcResearchTime(tech_id)
    #    else:
    #        return bot.handles[pid].calcShipDefenseTime(tech_id)
    elif name == "buildinfo":
        if not request.query.id:
            abort(403)
        return bot.handles[pid].fetchBuildInfo(int(request.query.id))
    elif name == "build":
        if not request.query.id:
            abort(403)
        if not request.query.count:
            count = 1
        else:
            count = request.query.count
        bot.handles[pid].build(int(request.query.id),count)
        redirect("/main/index.html")
    else:
        abort(403)

debug(True)
run(port=8080, reloader=True)
